import React, { Component } from 'react';
import { Space, Modal, Form, message, Tooltip } from "antd";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import { exportSheetTable } from '@/utils/exportTable.js';
import TextArea from "antd/es/input/TextArea";
import moment from 'moment'
import _ from "lodash";
import { getWithdrawalRecord, apiWithdrawalReview } from "@/request/distribution/withdrawManagement";

//提现申请
export default class AllList extends Component {
  state = {
    columns: [
      {
        title: "提现单号",
        dataIndex: "code",
        key: "code",
        width: 300
      },
      {
        title: "提现流水",
        dataIndex: "paymentPlatformCode",
        key: "paymentPlatformCode",
        width: 300
      },
      {
        title: '支付宝单号',
        dataIndex: 'paymentPlatformAlipayCode',
        key: 'paymentPlatformAlipayCode'
      },
      {
        title: "会员ID",
        dataIndex: "memberId",
        key: "memberId",
      },
      {
        title: "用户昵称",
        dataIndex: "memberNickName",
        key: "memberNickName",
      },
      {
        title: "会员手机号",
        dataIndex: "memberMobile",
        key: "memberMobile",
        render: (text) => {
          var reg = /^(\d{3})\d{4}(\d{4})$/;
          if (text) {
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        }
      },
      {
        title: "提现账户",
        dataIndex: "withdrawalAccountInfo",
        key: "withdrawalAccountInfo",
      },
      {
        title: "提现金额",
        dataIndex: "withdrawalAmount",
        key: "withdrawalAmount",
        render: (text, render) => {
          return <React.$Price price={text || 0} />
        },
      },
      {
        title: "提现时间",
        dataIndex: "createTime",
        key: "createTime",
        width: 200
      },
      {
        title: "到账时间",
        dataIndex: "amountReceivedTime",
        key: "amountReceivedTime",
        width: 200
      },
      {
        title: "提现状态",
        dataIndex: "status",
        key: "status",
        width: 200,
        render: (text, record) => {
          let str = '-';
          switch (text) {
            case 1:
              str = '待审核';
              break;
            case 2:
              str = <div style={{ display: 'flex', flexDirection: 'column' }}>
                <span>审核驳回</span>
                <span>({record.rejectReason})</span>
              </div>
              break;
            case 3:
              str = <div style={{ display: 'flex', flexDirection: 'column', }}>
                <span>到账失败</span>
                <span >({record.failedReason})</span>
              </div>
              break;
            case 4:
              str = '到账成功';
              break;
          }
          return <Tooltip title={str}>
            <div style={{ width: 200 }}>{str}</div>
          </Tooltip>
        },
      },
      {
        title: "出款账户",
        dataIndex: "disbursementAccountInfo",
        key: "disbursementAccountInfo",
        width: 200
      },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        render: (text, record) => {
          return (
            <div>
              {
                record.status === 1 && <>
                  <TheButton haspermi={['distribution:withdrawManagement:pass']} onClick={() => this.goPass(record)}>通过</TheButton>
                  <TheButton haspermi={['distribution:withdrawManagement:reject']} onClick={() => this.goReject(record)}>驳回</TheButton>
                </>
              }
              <TheButton haspermi={['distribution:withdrawManagement:view']} onClick={() => this.goView(record)}>账户明细</TheButton>
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    form_show: true,
    searchOption: [
      {
        field: 'memberInfo',
        label: '会员信息',
        placeholder: '输入会员ID/会员昵称/会员手机号',
        required: false,
        rules: [],
        type: 'Input',
        defaultValue: ''
      },
      {
        field: 'code',
        label: '提现单号',
        placeholder: '请输入',
        required: false,
        rules: [],
        type: 'Input',
        defaultValue: ''
      },
      {
        field: 'status',
        label: '提现状态',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [
          { value: '', label: '全部' },
          { value: 1, label: '待审核' },
          { value: 2, label: '被驳回' },
          { value: 3, label: '提现失败' },
          { value: 4, label: '已到账' },
        ],
        initialValues: ''
      },
      { field: 'time', label: '提现时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
    ],
    queryForm: {},
    passModalVisible: false,
    rejectModalVisible: false,
    withdrawalRecordId: '',//流水主键
    rejectLoading: false, //驳回loading
    passLoading: false, //通过loading
    exportLoading: false, // 导出loading
  }

  componentDidMount = async () => {
    this.getData()
  }
  /**
   * @desc 获取列表
   * */
  getData = async (value) => {
    const params = {
      ...this.state.pageData,
      ...this.state.queryForm,
    }
    getWithdrawalRecord({ ...params }).then(res => {
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount,
        })
      }
    })
  }
  /**
   * @desc 表格组件分页切换
   * @params number|string {pageNo} 页号
   * @params number|string {pageSize} 每页条数
   * */
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };
  /**
   * @desc 表格搜索组件重置搜索条件
   * */
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  /**
   * @desc 表格搜索组件搜索
   * */
  onFormSearch(value) {
    if (value && value.hasOwnProperty('time')) {
      value.createStartTime = moment(value.time[0]).format('yyyy-MM-DD') + ' 00:00:00'
      value.createEndTime = moment(value.time[1]).format('yyyy-MM-DD') + ' 23:59:59'
      delete value.time
    }
    let { queryForm } = this.state;
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: { ...value }
    }, () => {
      this.getData()
    })
  }
  /**
   * @desc 开启通过modal
   * */
  goPass = (values) => {
    this.setState({
      passModalVisible: true,
      withdrawalRecordId: values.withdrawalRecordId
    })
  }
  passModalOk = async () => {
    this.setState({ passLoading: true })
    // 通过提现申请
    let res = await apiWithdrawalReview({
      withdrawalRecordId: this.state.withdrawalRecordId,
      type: 1
    })
    if (res.code === 0) {
      message.success('申请通过')
      this.pageChange(1, 10)
      this.props.setTotal()
      this.setState({ passModalVisible: false })
    }
    this.setState({ passModalVisible: false, passLoading: false })
  }
  /**
   * @desc 开启驳回modal
   * */
  goReject = (values) => {
    this.setState({
      rejectModalVisible: true,
      withdrawalRecordId: values.withdrawalRecordId
    })
  }
  rejectModalOk = () => {
    this.setState({ rejectLoading: true })
    // 驳回提现申请
    this.formRef.validateFields().then(async (values) => {
      let res = await apiWithdrawalReview({
        ...values,
        withdrawalRecordId: this.state.withdrawalRecordId,
        type: 2
      })
      if (res.code === 0) {
        message.success('驳回成功')
      }
      this.pageChange(1, 10)
      this.props.setTotal()
      this.setState({ rejectModalVisible: false })
    })
    this.setState({ rejectLoading: false })
  }
  // 跳转明细
  goView = (values) => {
    this.props.history.push(`/distribution/sharerAccount/particulars/${values.memberId}`)
  }
  // 导出
  exportExcel = async () => {
    let { queryForm } = this.state;
    // if (_.isEmpty(queryForm)){
    //     Modal.warning({
    //         title: '提醒',
    //         content: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。',
    //     });
    //     return
    // }
    this.setState({ exportLoading: true })
    let params = {
      ...queryForm,
      pageNo: 1,
      pageSize: -1,
    }
    //
    let res = await getWithdrawalRecord({ ...params })
    if (res.code === 0) {
      let th_arr = [
        {
          title: '提现流水',
          prop: '',
          children: [
            {
              title: "提现单号",
              prop: "code",
            },
            {
              title: "提现流水",
              prop: "paymentPlatformCode",
            },
            { prop: 'paymentPlatformAlipayCode', title: '支付宝单号'},
            {
              title: "会员ID",
              prop: "memberId",
            },
            {
              title: "用户昵称",
              prop: "memberNickName",
            },
            {
              title: "会员手机号",
              prop: "memberMobile",
            },
            {
              title: "提现账户",
              prop: "withdrawalAccountInfo",
            },
            {
              title: "提现金额",
              prop: "withdrawalAmount",
            },
            {
              title: "提现时间",
              prop: "createTime",
            },
            {
              title: "到账时间",
              prop: "amountReceivedTime",
            },
            {
              title: "提现状态",
              prop: "status",
            },
            {
              title: "出款账户",
              prop: "disbursementAccountInfo",
            },
          ]
        },
      ]
      let tb_arr = []
      res.data.forEach((item, index) => {
        let str = '-';
        switch (item.status) {
          case 1:
            str = '待审核';
            break;
          case 2:
            str = `审核驳回(${item.rejectReason})`
            break;
          case 3:
            str = `到账失败(${item.failedReason})`
            break;
          case 4:
            str = '到账成功';
            break;
        }

        tb_arr.push({
          ...item,
          index: index + 1,
          status: str,
          withdrawalAmount: '￥' + (React.$transNum(item.withdrawalAmount, 2, -2)) || '￥0.00',
        })
      })
      exportSheetTable({
        fileName: '提现流水',
        tH_data: th_arr,
        tB_data: tb_arr,
        isSheet: true,
        merge: false
      })
    }
    this.setState({ exportLoading: false })
  }
  render() {
    let {
      passModalVisible,
      rejectModalVisible,
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      searchOption,
      form_show,
      rejectLoading,
      passLoading,
      exportLoading
    } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton haspermi={['distribution:withdrawManagement:export']} loading={exportLoading} type={'default'} size="middle" onClick={this.exportExcel}>导出</TheButton>
        </TheQueryForm>
        <TheTable
          scroll={{ x: '960', y: '63vh' }}
          columns={columns}
          dataSource={dataSource}
          rowKey={'withdrawalRecordId'}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        <Modal
          title="提醒"
          visible={passModalVisible}
          okText={"通过"}
          onOk={this.passModalOk}
          confirmLoading={passLoading}
          onCancel={() => this.setState({ passModalVisible: false })}
        >
          通过后，将自动给用户打款
        </Modal>
        <Modal
          title="提醒"
          visible={rejectModalVisible}
          okText={"驳回"}
          destroyOnClose={true}
          onOk={this.rejectModalOk}
          confirmLoading={rejectLoading}
          onCancel={() => this.setState({ rejectModalVisible: false })}
        >
          <Form
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 19,
            }}
            layout="horizontal"
            ref={(ref) => this.formRef = ref}
          >
            <Form.Item label="驳回原因" name={"content"} rules={[{ required: true }]}>
              <TextArea rows={4} maxLength={200} showCount allowClear />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
